<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no"/>
    <title></title>
    <!--使用本地选项卡时，将如下两行代码注释取消-->
    <!--<link rel="stylesheet" type="text/css" href="__wap2apptabbar.css" />
    <script src="__wap2apptabbar.js" type="text/javascript" charset="utf-8"></script>-->
</head>

<body>

<div>发送消息：</div>
<input type="text" id="msgContent"/>
<input type="button" value="发送" onclick="CHAT.chat()"/>

<div>接收消息：</div>
<div id="receiveMsg" style="background-color: gray;"></div>

<script type="application/javascript">

    window.CHAT = {
        socket: null,
        init: function () {
            if (window.WebSocket) {
                CHAT.socket = new WebSocket("ws://localhost:12171/ws");
                CHAT.socket.onopen = function () {
                    console.log("连接建立成功");
                },
                CHAT.socket.onclose = function () {
                    console.log("连接关闭");
                },

                CHAT.socket.onerror = function () {
                   console.log("连接出错");
                },

                CHAT.socket.onmessage = function (e) {
                console.log("接收到消息" + e.data);
                var message = document.getElementById("receiveMsg");
                var html = message.innerHTML;
                message.innerHTML = html + "<br />" + e.data;
                }
            } else {
                alert("浏览器不支持WebSocket");
            }
        },
        chat: function () {
            var message = document.getElementById("msgContent");

            CHAT.socket.send(message.value);
        }
    }

    CHAT.init();
</script>
</body>

</html>